package com.jinly.ryder.manage.web;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jinly.ryder.common.auth.annotation.Auth;
import com.jinly.ryder.common.auth.model.AuthRole;
import com.jinly.ryder.common.auth.model.AuthType;
import com.jinly.ryder.common.error.SystemErrorType;
import com.jinly.ryder.manage.service.HostInstanceService;
import com.jinly.ryder.manage.service.model.HostInstance;
import com.jinly.ryder.manage.web.mapping.HostInstanceVOMapping;
import com.jinly.ryder.manage.web.vo.HostInstanceVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("manage/host")
@RequiredArgsConstructor
public class HostInstanceController {

    private final HostInstanceVOMapping hostInstanceVOMapping;
    private final HostInstanceService hostInstanceService;

    @GetMapping("page")
    @Auth(type = AuthType.MANAGE, role = AuthRole.ADMIN, value = "app")
    public Page<HostInstanceVO> instancePage(Long current, Long size, HostInstanceVO query) {
        return hostInstanceVOMapping.toVOPage(hostInstanceService.instancePage(new Page(current, size), hostInstanceVOMapping.toModel(query)));
    }

    @PostMapping()
    @Auth(type = AuthType.MANAGE, role = AuthRole.ADMIN, value = "app")
    public void save(@RequestBody HostInstanceVO hostInstanceVO) {
        hostInstanceService.saveHost(hostInstanceVOMapping.toModel(hostInstanceVO));
    }

    @PostMapping("batch")
    @Auth(type = AuthType.MANAGE, role = AuthRole.ADMIN, value = "app")
    public void save(@RequestBody List<HostInstanceVO> list) {
        hostInstanceService.saveHost(hostInstanceVOMapping.toModelList(list));
    }


    @PostMapping("/import")
    @ResponseBody
    @Auth(type = AuthType.MANAGE, role = AuthRole.ADMIN, value = "app")
    public void importFile(@RequestParam("file") MultipartFile file) {
        BufferedReader reader = null;
        List<HostInstance> instanceList = new ArrayList<>();
        try {
            reader = new BufferedReader(new InputStreamReader(file.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                HostInstance hostInstance = parseLine(line);
                if (hostInstance != null) {
                    instanceList.add(hostInstance);
                }
            }
        } catch (Exception e) {
            log.error("解析文件失败", e);
            SystemErrorType.BAD_REQUEST.throwError("解析文件失败");
        } finally {
            try {
                if (reader != null) reader.close();
            } catch (Exception e) {
            }
        }
        hostInstanceService.saveHost(instanceList);

    }

    private HostInstance parseLine(String line) {
        if (line.startsWith("主机,名称,备注")) return null;
        log.info("upload host line=>{}", line);
        if (line.split(",").length == 3) {
            String[] ss = line.split(",");
            HostInstance hostInstance = new HostInstance();
            hostInstance.setName(formatStr(ss[1]));
            hostInstance.setHost(formatStr(ss[0]));
            hostInstance.setRemark(formatStr(ss[2]));
            return hostInstance;
        }
        return null;
    }

    private String formatStr(String s) {
        if (s != null) {
            s = s.trim();
        }
        if (ObjectUtils.isEmpty(s)) {
            return null;
        }
        return s;
    }
}
